package com.sinosoft.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/shiro")
@Controller
public class UserController {

	/**
	 * 测试SpringBoot项目
	 * @return
	 */
	@RequestMapping(value="/hello")
	@ResponseBody
	public String Hello() {
		System.out.println("SpringBoot项目启动了");
		return "OK";
	}
	
	/**
	 * 首页
	 * @param model
	 * @return
	 */
	@RequestMapping("/testThymeleaf")
	public String testThymeleaf(Model model) {
		model.addAttribute("name","SpringBoot-shiro");
		return "test";
	}
	
	/**
	 * 添加
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(Model model) {
		return "/user/add";
	}
	
	/**
	 * 更新
	 * @param model
	 * @return
	 */
	@RequestMapping("/update")
	public String update(Model model) {
		return "/user/update";
	}
	
	/**
	 * 未授权
	 * @param model
	 * @return
	 */
	@RequestMapping("/unAuth")
	public String unAuth(Model model) {
		return "/unauth";
	}
	
	
	/**
	 * 登陆跳转
	 * @param model
	 * @return
	 */
	@RequestMapping("/tologin")
	public String tologin(Model model) {
		return "/login";
	}
	
	
	
	
	/**
	 * 登陆
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String login(String username, String password,Model model) {
		System.out.println("有人在登陆，用户名是："+username);
		//获取subject对象
		Subject subject = SecurityUtils.getSubject();
		//封装用户数据
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		try {
			subject.login(usernamePasswordToken);	
			return "redirect:/shiro/testThymeleaf";
		} catch (AuthenticationException e) {
			model.addAttribute("msg", "用户名或密码不对");
			return "/login";
		}
	}
	
}
